const qiniuUploader = require("../../utils/qiniuUploader");
const util = require("../../utils/util");
var config = require("../../config");

//index.js

// 初始化七牛相关参数
function initQiniu() {
  var options = {
    region: 'SCN', // 华南区
    uptokenURL: config.urls.qiniu_uptoken,
    // uptoken: 'xxxx',
    domain: 'http://ottzwqsbr.bkt.clouddn.com',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    bookpic: {
      imageURL: "/images/icons/add.png"
    },
    name: "",
    author: "",
    press: "",
    published_date: util.formatDate2(new Date),

    book_id: -1,
    edit: false,
    picChanged: false
  },

  onLoad: function (options) {
    console.log('onLoad')
    var that = this;
    if (options.edit && options.edit == 'true') {
      //如果是编辑状态，就获取书籍信息
      var book_id = options.id;
      wx.request({
        url: config.urls.onebook,
        data: {
          id: book_id
        },
        success: function (res) {
          if (res.data.success) {
            var book = res.data.book;
            that.setData({
              name: book.name,
              author: book.author,
              press: book.press,
              published_date: book.published_date,
              bookpic: {
                imageURL: book.pic
              }
            });
          }
          else {
            console.log("no this book info: ", book_id);
          }
        }
      });

      that.setData({
        edit: true,
        book_id: book_id
      })
    }
  },

  formSubmit: function (e) {
    var that = this;
    console.log(e)
    var data = e.detail.value;
    console.log(data);
    var userInfo = getApp().globalData.userInfo;
    var bob_id = userInfo.id;
    var my_name = userInfo.nickname;

    if ((data.name == '')
      || (data.author == '')
      || (data.published_date == '')
      || (that.data.picChanged == false && that.data.edit == false)) {
      wx.showToast({
        title: '请提交书籍完整信息',
        icon: 'success',
        duration: 1500
      })
      return;
    }

    if (that.data.edit == false) {
      // 上架新书
      wx.request({
        url: config.urls.putaway,
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          name: data.name,
          author: data.author,
          press: data.press,
          published_date: data.published_date,
          pic: that.data.bookpic.imageURL,
          owner: bob_id,
          owner_name: my_name,
          city: 1
        },

        success: function (res) {
          if (res.data.success) {
            wx.showToast({
              title: '上架成功',
              icon: 'success',
              duration: 1500
            })
            wx.navigateBack({
              delta: 1
            })
          }
          else {
            wx.showToast({
              title: '上架失败',
              icon: 'loading',
              duration: 1500
            })
            console.log("Book upload failed.");
          }
        }
      });
    }
    else {
      // 编辑书
      wx.request({
        url: config.urls.editbook,
        method: "POST",
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          id: that.data.book_id,
          name: data.name,
          author: data.author,
          press: data.press,
          published_date: data.published_date,
          pic: that.data.bookpic.imageURL,
          city: 1
        },

        success: function (res) {
          if (res.data.success) {
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            })
            wx.navigateBack({
              delta: 1
            })
          }
          else {
            wx.showToast({
              title: '提交失败',
              icon: 'loading',
              duration: 1500
            })
            console.log("Book edit failed.");
          }
        }
      });
    }
  },

  cancel: function (e) {
    wx.navigateBack({
      delta: 1
    })
  },

  bindDateChange: function (e) {
    this.setData({
      published_date: e.detail.value
    })
  },

  onShelfBook: function (e) {
    var that = this;
    initQiniu();
    // 微信 API 选文件
    wx.chooseImage({
      count: 1,
      success: function (res) {
        var filePath = res.tempFilePaths[0];
        // 交给七牛上传
        qiniuUploader.upload(filePath, (res) => {
          that.setData({
            'bookpic': res,
            'picChanged': true
          });
        }, (error) => {
          console.error('error: ' + JSON.stringify(error));
        });
      }
    })

  }
})
